package com.itheima.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.aspectj.apache.bcel.generic.RET;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * @author ：Qifei
 * @date ：Created in 2020/8/6 20:23
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    JedisPool jedisPool;
    @Autowired
    DefaultKaptcha defaultKaptcha;


    @RequestMapping("/code/{deviceId}")
    public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
        Assert.notNull(deviceId, "机器码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = defaultKaptcha.createText();
        System.out.println("图形验证码 : " + text);
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);

        //生成的验证码写入redis
        jedisPool.getResource().setex(deviceId,60*5,text);
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        //将图片写回浏览器
        ImageIO.write(image, "JPEG", out);
    }
}
